package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.CecBaseMapper;
import net.yunxinyong.sign.mapper.CecOneMapper;
import net.yunxinyong.sign.mapper.CecTwoMapper;
import net.yunxinyong.sign.service.CecBaseService;
import net.yunxinyong.sign.service.CecOneService;
import net.yunxinyong.sign.service.CecTwoService;
import net.yunxinyong.sign.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecTwoServiceImpl implements CecTwoService {
    @Autowired
    private CecTwoMapper cecTwoMapper;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private CecBaseService cecBaseService;
    @Override
    public CecTwo select(int invid) {
        CecTwoExample cecTwoExample = new CecTwoExample();
        //id和企业状态为正常作为查询条件
        cecTwoExample.createCriteria().andInvIdEqualTo(invid).andStatusEqualTo(0);
        List<CecTwo> list = cecTwoMapper.selectByExample(cecTwoExample);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void update(CecTwo cecTwo, Integer adminId) {
        cecTwo.setUpdateTime(new Date());
        int count = cecTwoMapper.updateByPrimaryKey(cecTwo);
        Integer update = baseAndTwoLogic1(cecTwo);
        boolean insert = recordService.insert(adminId, cecTwo.getInvId(), null, 12);
        if (count <= 0 || !insert || update <= 0) {
            throw new CECException(501, "更新失败!");
        }
    }

    @Override
    public void insert(CecTwo cecTwo, Integer adminId) {
        cecTwo.setUpdateTime(new Date());
        cecTwo.setCreateTime(new Date());
        cecTwo.setStatus(0);
        int count = cecTwoMapper.insert(cecTwo);
        Integer update = baseAndTwoLogic1(cecTwo);
        boolean insert = recordService.insert(adminId, cecTwo.getInvId(), null, 12);
        if (count <= 0 || update <= 0  || !insert) {
            throw new CECException(501, "添加失败!");
        }
    }

    public Integer baseAndTwoLogic1(CecTwo cecTwo){
        //在往2表插入数据的同时，更新base表中192项的数据。。。
        CecBase cecBase = cecBaseService.select(cecTwo.getInvId());
        if (cecBase != null){
            cecBase.setEmployee(cecTwo.getFinalEmployeesNumber());
            cecBase.setFemale(cecTwo.getFemaleNumber());
            return cecBaseMapper.updateByPrimaryKeySelective(cecBase);
        }
        return null;
    }
}
